import javax.telephony.Provider;
import javax.telephony.JtapiPeer;
import javax.telephony.JtapiPeerFactory;

import javax.telephony.*;
import javax.telephony.events.*;
import javax.telephony.callcontrol.*;
import javax.telephony.callcontrol.events.*;

/*
 * The MyCallCtlInCallObserver class implements the CallControlCallObserver and
 * recieves all Call-related events.
 */

class MyCallCtlInCallObserver implements CallControlCallObserver {

	public void callChangedEvent(CallEv[] evlist) {

		for (int i = 0; i < evlist.length; i++) {

			if (evlist[i] instanceof TermConnEv) {
				TerminalConnection termconn = null;
				String name = null;

				try {
					TermConnEv tcev = (TermConnEv) evlist[i];
					Terminal term = termconn.getTerminal();
					termconn = tcev.getTerminalConnection();
					name = term.getName();
				} catch (Exception excp) {
					// Handle exceptions.
				}

				String msg = "TerminalConnection to Terminal: " + name + " is ";

				if (evlist[i].getID() == CallCtlTermConnTalkingEv.ID) {
					System.out.println(msg + "TALKING");
				} else if (evlist[i].getID() == CallCtlTermConnRingingEv.ID) {
					System.out.println(msg + "RINGING");

					/* Answer the telephone Call using "inner class" thread */

					try {
						final TerminalConnection _tc = termconn;
						Runnable r = new Runnable() {
							public void run() {
								try {
									_tc.answer();
								} catch (Exception excp) {
									// Handle answer exceptions
								}
							};
						};
						Thread T = new Thread(r);
						T.start();
					} catch (Exception excp) {
						// Handle Exceptions;
					}
				} else if (evlist[i].getID() == CallCtlTermConnDroppedEv.ID) {
					System.out.println(msg + "DROPPED");
				}
			}
		}
	}
}
